import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RangModule } from './rang/rang.module';
import { ConfigModule } from '@nestjs/config';
import * as dotenv from 'dotenv';
import * as Joi from 'joi';
const envFilePath = `.env.${process.env.NODE_MODE}`;
const schema = Joi.object({
  DB: Joi.string().required(),
  DB_HOST: Joi.number().default(3306),
  BASE_URL: Joi.alternatives().try(Joi.string().ip(), Joi.string().domain()),
  DB_TYPE: Joi.string().valid('mysql', 'postgres'),
});
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // 全局使用配置文件
      envFilePath,
      load: [
        () => {
          // fix: config模块对于load方法无法进行校验的bug
          const values = dotenv.config({ path: '.env' });
          const { error } = schema.validate(values?.parsed, {
            allowUnknown: true,
            abortEarly: false,
          });
          if (error) {
            throw new Error(
              `Validation failed - Is there an environment variable missing?${error.message}`,
            );
          }
          return values;
        },
      ],
      validationSchema: schema,
    }),
    RangModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
